var websock = null;

var global_callback = null;
var timeout = 5000; // 心跳检测5秒
var serverPort = "2233"; // webSocket连接端口
// var wsuri = "ws://127.0.0.1:" + serverPort;
// console.log('window.location.hostname::', window.location.hostname);
const protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://'; 
// 测试 ： trading_h5.metatravers3.com
// 正式 ： api.trading28.com
var host = process.env.NODE_ENV === 'production' ? window.location.hostname : 'trading_h5.metatravers3.com'
var wsuri = `${protocol}${host}/ws`
// var wsuri = `wss://rollbit.metatravers7.com/ws`
// console.log('wsuri', wsuri, window.location);

let serverTimeoutObj;

function createWebSocket(callback) {

	if (websock == null || typeof websock !== WebSocket) {
		initWebSocket(callback);
	}
}

function initWebSocket(callback) {
	global_callback = callback;
	// 初始化websocket
	websock = new WebSocket(wsuri);
	websock.onmessage = function(e) {
		// heartCheckReset();
		// heartCheckStart(global_callback)
		websocketonmessage(e);
	};
	websock.onclose = function(e) {
		websocketclose(e);
		global_callback({
			'type': 'close'
		})
	};
	websock.onopen = function() {
		heartCheckReset();
		heartCheckStart(global_callback)
		websocketOpen();
		global_callback({
			'type': 'open'
		})
	};

	// 连接发生错误的回调方法
	websock.onerror = function() {
		// console.log("WebSocket连接发生错误");
		//createWebSocket();啊，发现这样写会创建多个连接，加延时也不行
	};
}

// 实际调用的方法
function sendSock(agentData) {

	if (websock.readyState === websock.OPEN) {
		// 若是ws开启状态
		websocketsend(agentData);
	} else if (websock.readyState === websock.CONNECTING) {
		// 若是 正在开启状态，则等待1s后重新调用
		setTimeout(function() {
			sendSock(agentData);
		}, 1000);
	} else {
		// 若未开启 ，则等待1s后重新调用
		setTimeout(function() {
			sendSock(agentData);
		}, 1000);
	}
}

function closeSock() {
	websock?.close();
}

// 数据接收
function websocketonmessage(msg) {
	// console.log("收到数据："+JSON.parse(e.data));
	// console.log("收到数据：" + msg);

	// global_callback(JSON.parse(msg.data));

	// 收到信息为Blob类型时
	let result = null;
	// debugger
	if (msg.data instanceof Blob) {
		const reader = new FileReader();
		reader.readAsText(msg.data, "UTF-8");
		reader.onload = (e) => {
			result = JSON.parse(reader.result);
			//console.log("websocket收到", result);
			global_callback(result);
		};
	} else {
		try {
			result = JSON.parse(msg.data)
		} catch {
			result = msg
		}
		//console.log("websocket收到", result);
		global_callback(result);
	}
}

// 数据发送
function websocketsend(agentData) {
	// console.log("发送数据：" + agentData);
	websock.send(agentData);
}

// 关闭
function websocketclose(e) {
	heartCheckReset();
	// console.log('websocketclose', e);
	// console.log("connection closed (" + e.code + ")");
}

function websocketOpen(e) {
	console.log("连接打开", e);
}

// 心跳检测, 每隔一段时间检测连接状态，如果处于连接中，就向server端主动发送消息，来重置server端与客户端的最大连接时间，如果已经断开了，发起重连。
function heartCheckReset() {
	clearTimeout(serverTimeoutObj);
}

function heartCheckStart(active) {
	serverTimeoutObj = setTimeout(() => {
		if (websock.readyState == 1) {
			// console.log("websocket连接状态，发送心跳检测ping维持心跳连接...");
			let ping = {
				type: 'ping'
			}
			websock.send(JSON.stringify(ping));
			//如果获取到消息，说明连接是正常的，重置心跳检测
			heartCheckReset();
			heartCheckStart(active);
		} else {
			// console.log("websocket断开状态，尝试重连");
			createWebSocket(active);
		}
	}, timeout)
}

export {
	sendSock,
	createWebSocket,
	closeSock
};